<?php

/**
 * Класс работы с изображениями
 */
class ImagesModel {

    /**
     * Изменение размера изображения
     *
     * @param string $src
     * @param int $width
     * @param int $height
     * @param bool $crop
     * @return type 
     */
    /*
      if (!$_img || false == ($_out = imagecreatetruecolor($w, $h))) {
      return false;
      }
      if (!imagecopyresampled($_out, $_img, 0, 0, 0, 0, $w, $h, $s[0], $s[1])) {
      return false;
      } */

    function image_resize($src, $width, $height, $crop=1) {

        if (!list($w, $h) = getimagesize($src))
            return false;

        $type = strtolower(substr(strrchr($src, "."), 1));
        if ($type == 'jpeg')
            $type = 'jpg';
        switch ($type) {
            case 'gif': $img = imagecreatefromgif($src);
                break;
            case 'jpg': $img = imagecreatefromjpeg($src);
                break;
            case 'png': $img = imagecreatefrompng($src);
                break;
            default : return false;
        }

        // resize
        if ($crop) {
            if ($w < $width or $h < $height) {
                $x = 0;
            } else {
                $ratio = max($width / $w, $height / $h);
                $h = $height / $ratio;
                $x = ($w - $width / $ratio) / 2;
                $w = $width / $ratio;
            }
        } else {
            if ($w < $width and $h < $height) {
                $x = 0;
            } else {
                $ratio = min($width / $w, $height / $h);
                $width = $w * $ratio;
                $height = $h * $ratio;
                $x = 0;
            }
        }

        $new = imagecreatetruecolor($width, $height);

        // preserve transparency
        if ($type == "gif" or $type == "png") {
            imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
            imagealphablending($new, false);
            imagesavealpha($new, true);
        }

        imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);

        switch ($type) {
            case 'gif': imagegif($new, $src);
                break;
            case 'jpg': imagejpeg($new, $src);
                break;
            case 'png': imagepng($new, $src);
                break;
        }

        imagedestroy($new);
        imagedestroy($img);

        return true;
    }

    /**
     * Обрезание картинки
     *
     * @param file $img
     * @param int $w
     * @param int $h
     * @return img
     */
    public function tmb($img, $w, $h) {
        if (false == ($s = getimagesize($img))) {
            return false;
        }
        //$tmbSize = $this->_options['tmbSize'];
        if ($s['mime'] == 'image/jpeg') {
            $_img = imagecreatefromjpeg($img);
        } elseif ($s['mime'] == 'image/png') {
            $_img = imagecreatefrompng($img);
        } elseif ($s['mime'] == 'image/gif') {
            $_img = imagecreatefromgif($img);
        }
        if (!$_img || false == ($_tmb = imagecreatetruecolor($w, $h))) {
            return false;
        }
        list($x, $y, $size) = $this->_cropPos($s[0], $s[1]);
        if (!imagecopyresampled($_tmb, $_img, 0, 0, $x, $y, $w, $h, $size, $size)) {
            return false;
        }

        //Сохраняем
        if ($s['mime'] == 'image/jpeg') {
            $r = imagejpeg($_tmb, $img, 100);
        } else if ($s['mime'] == 'image/png') {
            $r = imagepng($_tmb, $img, 7);
        } else {
            $r = imagegif($_tmb, $img, 7);
        }

        imagedestroy($_img);
        imagedestroy($_tmb);
        return $r;
        break;
    }

    /**
     * Обновление аватарки и фотографии в профиле пользователя
     *
     * @param file $img
     * @param uid $uid
     * @return <type>
     */
    public function updatePhoto($img, $uid, $w = 200, $h = 300, $a = 50) {

        $config = Zend_Registry::get('config');
        if (false == ($s = getimagesize($img))) {
            return false;
        }
        if ($s['mime'] == 'image/jpeg') {
            $end = '.jpg';
        } else if ($s['mime'] == 'image/png') {
            $end = '.png';
        } else {
            $end = '.gif';
        }

        if (!file_exists(PUBLIC_PATH . MEDIA_PATH . '/avatars'))
            mkdir(PUBLIC_PATH . MEDIA_PATH . '/avatars');
        $photo = PUBLIC_PATH . MEDIA_PATH . '/avatars/' . $uid . $end;
        $avatar = PUBLIC_PATH . MEDIA_PATH . '/avatars/' . $uid . 'a' . $end;

        copy($img, $photo);
        copy($photo, $avatar);
        $p = $this->resizeImg($photo, $w, $h);
        $a = $this->tmb($avatar, $a, $a);
        return true;
    }

    /**
     * Обновление аватарки и фотографии в профиле пользователя
     *
     * @param link $img
     * @return <type>
     */
    public function updateImage($img, $w, $h, $p = false, $pw = 0, $ph = 0) {
        $img = PUBLIC_PATH . $img;
        if (false == ($s = getimagesize($img))) {
            return false;
        }
        if ($s['mime'] == 'image/jpeg') {
            $end = '.jpg';
        } else if ($s['mime'] == 'image/png') {
            $end = '.png';
        } else {
            $end = '.gif';
        }
        $path = pathinfo($img, PATHINFO_DIRNAME);
        $filename = pathinfo($img, PATHINFO_FILENAME);

        $image = $path . '/' . $filename . '_i' . $end;
        $preview = $path . '/' . $filename . '_p' . $end;
        if ($w > 0 && $h > 0) {
            copy($img, $image);
            $i = $this->image_resize($image, $w, $h, true);
        } else {
            return false;
        }

        if ($p == 1 && $pw > 0 && $ph > 0) {
            copy($img, $preview);
            $p = $this->image_resize($preview, $pw, $ph, true);
        }

        return true;
    }
    
    public function getUrl($src, $preview = false) {
        $img = PUBLIC_PATH . $src;
        if (!file_exists($img))
            return false;
        $path = pathinfo($src, PATHINFO_DIRNAME);
        $filename = pathinfo($img, PATHINFO_FILENAME);
        $ext = pathinfo($img, PATHINFO_EXTENSION);
        if ($preview) {
            $end = '_p';
        } else {
            $end = '_i';
        }
            
        return SITE_URL . $path . '/' . $filename . $end . '.' . $ext;
    }

    /**
     * Получение пути аватарки
     *
     * @param int $uid #ID Пользователя
     * @return str URL
     */
    public function getAvatar($uid = 0) {
        if ($uid > 0) {
            $mime = array('.jpg', '.gif', '.png');
            foreach ($mime as $value) {
                if (file_exists(PUBLIC_PATH . MEDIA_PATH . '/avatars/' . $uid . 'a' . $value))
                    return SITE_URL . MEDIA_PATH . '/avatars/' . $uid . 'a' . $value;
            }
        }
        return SITE_URL . MEDIA_PATH . '/avatars/avatar.png';
    }

    /**
     * Get either a Gravatar URL or complete image tag for a specified email address.
     *
     * @param string $email The email address
     * @param string $s Size in pixels, defaults to 80px [ 1 - 512 ]
     * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
     * @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
     * @param boole $img True to return a complete IMG tag False for just the URL
     * @param array $atts Optional, additional key/value attributes to include in the IMG tag
     * @return String containing either just a URL or a complete image tag
     * @source http://gravatar.com/site/implement/images/php/
     */
    function getGravatar($email, $s = 50, $d = 'identicon', $r = 'g', $img = false, $atts = array()) {
        $url = 'http://www.gravatar.com/avatar/';
        $url .= md5(strtolower(trim($email)));
        $url .= "?s=$s&d=$d&r=$r";
        if ($img) {
            $url = '<img src="' . $url . '"';
            foreach ($atts as $key => $val)
                $url .= ' ' . $key . '="' . $val . '"';
            $url .= ' />';
        }
        return $url;
    }

    private function _cropPos($w, $h) {
        $x = $y = 0;
        $size = min($w, $h);
        if ($w > $h) {
            $x = ceil(($w - $h) / 2);
        } else {
            $y = ceil(($h - $w) / 2);
        }
        return array($x, $y, $size);
    }

}